from .marketing_coupon_func import MarketingCouponFunc
from ...rp_customer_management.functions.flow_log_functions import FlowLogFunctions
from ...rp_customer_management.models.primary.rp_flow_log import RECORD_SELECTION, CHANGE_TYPE

from odoo.exceptions import UserError

SCHEDULE_TYPE = [('birth', '生日'), ('register', '注册')]


class MarketingScheduleFunc(object):
    """
   Model:
        满足所有运营任务（自动和手动）的逻辑
    
    Params:
        -env:odoo env 
    """

    def __init__(self, env, clr):
        self.env = env
        self.this = clr

    """
    ------------------------------------------------------------
    自动任务相关逻辑
    """

    def active_auto_schedule(self, map_data):
        """
        激活自动任务
        Params:
        -result:自动任务记录
        -map_data:传递参数映射
        """
        data = {
            'name': map_data['name'],
            'user_id': self.env.ref('base.user_root').id,
            'model_id': self.env.ref('rp_marketing_management.model_rp_marketing_auto_schedule').id,
            'state': 'code',
            'code': map_data['code'],
            'interval_number': map_data['interval_number'],
            'interval_type': map_data['interval_type'],
            'numbercall': map_data['numbercall'],
            'rp_marketing_auto_schedule_id': map_data['rp_marketing_auto_schedule_id'],
            'auto_schedule_tag': map_data['auto_schedule_tag'],
            'active': True
        }
        self.env['ir.cron'].create([data])

    def build_domain(self, customer_category_ids, customer_level_ids, customer_ids):
        """
        构建筛选域
        Params:
        -customer_category_ids:客户分类
        -customer_level_ids:客户等级
        -customer_ids:客户
        """
        # 客户已选情况
        if len(customer_ids) > 0:
            domain_list = [('id', 'in', customer_ids)]
            return domain_list
        # 客户未选的情况
        domain_list = []
        if len(customer_category_ids) > 0:
            domain_list.append(('rp_customer_category', 'in', customer_category_ids.ids))
        if len(customer_level_ids) > 0:
            domain_list.append(('customer_level', 'in', customer_level_ids.ids))
        return domain_list

    def issue_coupon_and_cash(self, customer, record):
        """
        返现和返优惠券
        Params:
        -customer:客户
        -record:任务记录
        """
        # 返现
        if record.cash_back_tag:
            price = customer.remaining_sum + record.cash_back_price
            customer.write({'remaining_sum': price})
            root_category = self.env['rp.flow.record.category'].search([('name', '=', '任务')])
            sec_category = self.env['rp.flow.record.category'].search([('name', '=', '自动任务'), ('parent_category_id', '=', root_category.id)])
            # 创建流水记录
            log_detail_list = [(0, 0, {'flow_record_category_id': sec_category.id, 'change_type': CHANGE_TYPE[0][0], 'funds_change': record.cash_back_price, 'desc': f'生日自动任务（{record.code}）：' + str(record.cash_back_price) + '€'})]
            FlowLogFunctions(self.env).save_flow_log(rp_customer_id=customer.id, category_id=root_category.id, related_record=RECORD_SELECTION[2][0] + ',' + str(record.id),
                                                     change_type=CHANGE_TYPE[0][0], funds_change=record.cash_back_price, rp_flow_record_log_line_ids=log_detail_list)
        # 返优惠券
        if record.coupon_issue_tag:
            coupon_lines = record.coupon_line_display_ids
            for coupon_line in coupon_lines:
                for i in range(coupon_line.amount):
                    MarketingCouponFunc(self.env).issue_coupon_to_customer(coupon_line.rp_coupon_template_id, customer)

    def handle_history_record(self, code, fixed_customer_tag, rp_customer_ids, customer_level_ids, customer_category_ids, schedule_type):
        """
        处理历史记录，并校验逻辑
        Params:
        -code:编码
        -fixed_customer_tag:固定客户标志
        -rp_customer_ids:固定客户
        -customer_level_ids:客户等级
        -customer_category_ids:客户分类
        -schedule_type:任务类型
        """
        # 如果记录设定有用户集，搜寻历史中是否有同样的用户集【忽略等级分类影响】
        equal_ids = []
        base_search_ids = self.env['rp.marketing.auto.schedule'].search([('code', '!=', code), ('schedule_state', '=', 'done'), ('schedule_type', '=', schedule_type)])
        if fixed_customer_tag:
            schedule_ids = base_search_ids.filtered(lambda r: set(r.rp_customer_ids.ids) & set(rp_customer_ids))
            if len(schedule_ids) > 0:
                difference_record_codes = '[' + ','.join(schedule_ids.mapped(lambda r: r.code)) + ']'
                raise UserError(f' {difference_record_codes} 和本规则存在冲突，解决后重试!     (处理用户冲突)')
            # 查找相同记录,相同记录直接覆盖
            equal_ids = base_search_ids.filtered(lambda r: set(r.rp_customer_ids.ids) == set(rp_customer_ids))
        else:
            # 记录中没有选择用户，考虑分类和等级的影响（分类和等级都存在交集的情况下不进行添加）
            if len(customer_level_ids) > 0 and len(customer_category_ids) > 0:
                equal_ids = base_search_ids.filtered(lambda r: set(r.customer_level_ids.ids) == set(customer_level_ids) and set(r.customer_category_ids.ids) == set(customer_category_ids))
                customer_conflict = base_search_ids.filtered(lambda r: set(r.customer_level_ids.ids) & set(customer_level_ids) and set(r.customer_category_ids.ids) & set(customer_category_ids))
                if len(customer_conflict.ids) > 0 and len(equal_ids.ids) == 0:
                    difference_record_codes = '[ ' + ', '.join(set(customer_conflict.mapped(lambda r: r.code))) + ']'
                    raise UserError(f' {difference_record_codes} 和本规则存在冲突，解决后重试!   (处理等级或分类冲突)')
            else:
                raise UserError('配置错误！')
        return equal_ids

    def create_adjust_template_auto_validate_expired_log(self, adjustment_template_ids, tag):
        """
        创建调价模板自动生效，过期日志
        Params:
        -adjustment_template_ids:调价模板
        -tag:标志 True-自动生效  False-自动过期
        """
        operation_desc = '调价模板' + ('生效' if tag else '过期') + '【' + ''.join(adjustment_template_ids.mapped(lambda r: f'{r.name}({r.code})')) + '】'
        values = {
            'origin_from': 'system',
            'schedule_type': 'auto',
            'operation_desc': operation_desc
        }
        self.env['rp.marketing.schedule.log'].create([values])

    """
       ------------------------------------------------------------------
       手动任务相关逻辑
       """

    def manual_issue_coupon_and_cash(self, customer, price_operation, cash_back_price, issue_coupon_line_ids):
        """
        返现和返优惠券（手动任务）
        Params:
        -customer:客户
        -price_operation:操作类型 【add,subtract】
        -cash_back_price:返现金额
        -issue_coupon_line_ids:发送的优惠券详情
        """
        # 返现
        if cash_back_price > 0:
            price = customer.remaining_sum + cash_back_price if price_operation == 'add' else customer.remaining_sum - cash_back_price
            customer.write({'remaining_sum': price})
            root_category = self.env['rp.flow.record.category'].search([('name', '=', '任务')])
            sec_category = self.env['rp.flow.record.category'].search([('name', '=', '手动任务'), ('parent_category_id', '=', root_category.id)])
            # 创建流水记录
            operation = CHANGE_TYPE[0][0] if price_operation == 'add' else CHANGE_TYPE[1][0]
            desc = '+' if price_operation == 'add' else '-'
            log_detail_list = [(0, 0, {'flow_record_category_id': sec_category.id, 'change_type': operation, 'funds_change': cash_back_price, 'desc': f'手动任务：{desc}' + str(cash_back_price) + '€'})]
            FlowLogFunctions(self.env).save_flow_log(rp_customer_id=customer.id, category_id=root_category.id, change_type=operation, funds_change=cash_back_price, rp_flow_record_log_line_ids=log_detail_list)
        # 返优惠券
        if len(issue_coupon_line_ids.ids) > 0:
            for coupon_line in issue_coupon_line_ids:
                for i in range(coupon_line.amount):
                    MarketingCouponFunc(self.env).issue_coupon_to_customer(coupon_line.rp_coupon_template_id, customer)

    def record_the_schedule_log(self, customer_ids, price_change_type, cash_back_price, coupon_issue_line_ids, operation_type, operation_person, record_id=None):
        """
        记录任务日志
        Params:
        -customer_ids:客户集合
        -price_change_type:资金变动方式
        -cash_back_price:资金变动金额
        -manual_coupon_issue_line_ids:发放的优惠券明细
        -record_id:记录ID
        -operation_type:操作类型
        -operation_person:操作人
        """
        desc = ''
        if cash_back_price != 0:
            if price_change_type == 'add':
                price_desc = '+' + str(cash_back_price) + '€'
            else:
                price_desc = '-' + str(cash_back_price) + '€'
            desc = desc + '余额变化:' + price_desc + '\n'
        if len(coupon_issue_line_ids.ids):
            coupon_desc = '【' + ','.join(coupon_issue_line_ids.mapped(lambda r: r.name_display)) + '】'
            desc = desc + '优惠券：' + coupon_desc

        values = {
            'operation_person': operation_person.id,
            'schedule_type': operation_type,
            'target_customers': [(6, 0, customer_ids.ids)],
            'operation_desc': desc
        }
        if record_id:
            values['reference_record'] = record_id
        self.env['rp.marketing.schedule.log'].create([values])
